 //
//  SRManager.m
//  SportRing
//
//  Created by mykoma on 14-4-12.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRManager.h"
#import "LGBluetoothCentralManager.h"
#import "SRSportNetService.h"
#import "SRTimeService.h"
#import "SRAlarmService.h"
#import "SRTaskService.h"
#import "SRDB.h"
#import "BlueToothLib.h"
#import "SRSportBleService.h"
#import "SRBatteryService.h"
#import "SRAccountNetService.h"

@interface SRManager() <LGBluetoothCentralManagerDelegate>

@property (nonatomic, assign) BOOL hasSycBLE;
@property (nonatomic, assign) BOOL hasConnected;
@property (nonatomic, copy) NSString * peripheralName;

@end

@implementation SRManager

CWL_SYNTHESIZE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(SRManager, sharedInstance);

- (id)init
{
    self = [super init];
    if (self) {
        self.findDevices = [@[] mutableCopy];
        self.hasSycBLE = NO;
        self.hasConnected = NO;
        [LGBluetoothCentralManager sharedInstance].delegate = self;
        [SRAlarmService addObserverForBleData];
        [SRSportBleService addObserverForBleData];
        [SRBatteryService addObserverForBleData];
    }
    return self;
}

-(void)readyToStartUp
{
    if (self.hasConnected) {
        [self syncWithBLEDeivce];
    }
    [self uploadSportParts];
    [self uploadSleeps];
    [self uploadSportTask];
}

-(void)syncWithBLEDeivce
{
    self.hasSycBLE = YES;
    @weakify(self);
    // 蓝牙同步
    [[[[[SRTimeService updateCurrentTimeToDevie] flattenMap:^RACStream *(id value) {
        return [SRBatteryService readBatteryFromDevice];
    }] flattenMap:^RACStream *(id value) {
        return [SRSportBleService readSleepData];
    }] flattenMap:^RACStream *(id value) {
        return [SRSportBleService readUnSyncSportData];
    }] subscribeNext:^(id x) {
        [self_weak_ uploadSportParts];
        [self_weak_ uploadSleeps];
        [self_weak_ uploadSportTask];
    }];
}

- (void)uploadSportParts
{
    NSArray * array = [SRSportPart findAllUnuploadSportParts:[SRMe currentUser]];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [SRSportNetService uploadSportPart:obj];
    }];
}

-(void)uploadSleeps
{
    NSArray * array = [SRSleep findAllUnuploadSleep:[SRMe currentUser]];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [SRSportNetService uploadSleepWithSleep:obj];
    }];
}

- (void)uploadSportTask
{
    NSArray * array = [SRSportTask findAllUnuploadTasks:[SRMe currentUser]];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [SRSportNetService uploadTask:obj];
    }];
}

- (void)setCurrentPeripheralName:(NSString *)peripheralName
{
    _peripheralName = peripheralName;
    if (_peripheralName) {
        [self findPeripheralAndConnect];
    }
}

-(void)findPeripheralAndConnect
{
    @weakify(self);
    [self.findDevices enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        YMSCBPeripheral * per = obj;
        if ([per.name isEqualToString:self_weak_.peripheralName]) {
            self_weak_.peripheral = per;
            *stop = YES;
        }
    }];
    [self actionToConnect];
}

-(void)actionToConnect
{
    if (self.peripheral) {
        @weakify(self);
        [self connectToDeviceWithBlock:^(id data) {
            if ([data isKindOfClass:[NSData class]]) {
                NSLog(@"连接蓝牙成功...");
                self_weak_.hasConnected = YES;
            }
        }];
    }
}

-(void)connectToDeviceWithBlock:(CompletionBlock)block
{
    @weakify(self);
    [[LGBluetoothCentralManager sharedInstance] connectTo:self.peripheral withBlock:^(id data) {
        
        if (![data isKindOfClass:[NSData class]]) {
            block(nil);
            return ;
        }
        
        self_weak_.hasConnected = YES;
        
        static const char * UUID = "\x6E\x40\x00\x03\xB5\xA3\xF3\x93\xE0\xA9\xE5\x0E\x24\xDC\xCA\x9E";
        NSData * uuidData = [NSData dataWithBytes:UUID length:16];
        CBUUID * uuid = [CBUUID UUIDWithData:uuidData];
        [[LGBluetoothCentralManager sharedInstance] listenForUUID:uuid
                                                            block:^(id data)
         {
             CBCharacteristic * ch = data;
             NSLog(@"LISTEN:  %@", ch.value);
             if (ch.value != nil) {
                 [BlueToothLib receivedResponse:ch.value];
             }
         }];
        
        if (!self_weak_.hasSycBLE && [SRMe currentUser] != nil) {
            [self_weak_ syncWithBLEDeivce];
        }
        block(data);
    }];
}

-(void)updateCharacteristicUUID:(CBUUID *)uuid
                      withValue:(NSData *)data
                     completion:(CompletionBlock)block
{
    if (self.hasConnected == NO) {
        dispatch_async(dispatch_get_main_queue(), ^{
            block(nil);
        });
    }
    else
    {
        [[LGBluetoothCentralManager sharedInstance] updateCharacteristicUUID:uuid
                                                                   withValue:data
                                                                  completion:block];
    }
}

-(void)disconnectWithDevice
{
    self.peripheral = nil;
    self.hasSycBLE = NO;
    [[LGBluetoothCentralManager sharedInstance] disconnectWithDevice];
}

-(void)setCurrentUserName:(NSString *)name
{
}

#pragma mark - CBCentralManagerDelegate

-(NSArray *)deviceFilterPrefixName
{
    return @[@"IMCO"];
}

-(NSDictionary *)validServicesUUIDs
{
    const char * deviceUUID = "\x6E\x40\x00\x01\xB5\xA3\xF3\x93\xE0\xA9\xE5\x0E\x24\xDC\xCA\x9E";
    NSData * deviceDataUUID = [NSData dataWithBytes:deviceUUID length:16];
    
    const char * batteryUUID = "\x18\x0f";
    NSData * batteryUUIDData = [NSData dataWithBytes:batteryUUID length:2];
    
    return @{@"deviceDataService" : deviceDataUUID,
             @"batteryService" : batteryUUIDData};
}

-(NSDictionary *)validCharacteristics
{
    NSMutableDictionary * characteristics = [NSMutableDictionary dictionary];
    
    const char * writeUUID = "\x6E\x40\x00\x02\xB5\xA3\xF3\x93\xE0\xA9\xE5\x0E\x24\xDC\xCA\x9E";
    NSData * userInfoData = [NSData dataWithBytes:writeUUID length:16];
    characteristics[@"writeUUID"] = userInfoData;
    
    const char * readUUID = "\x6E\x40\x00\x03\xB5\xA3\xF3\x93\xE0\xA9\xE5\x0E\x24\xDC\xCA\x9E";
    NSData * timeData = [NSData dataWithBytes:readUUID length:16];
    characteristics[@"readUUID"] = timeData;

    const char * batteryUUID = "\x2a\x19";
    NSData * batteryUUIDData = [NSData dataWithBytes:batteryUUID length:2];
    characteristics[@"BatteryUUID"] = batteryUUIDData;
    
    return [NSDictionary dictionaryWithDictionary:characteristics];
}

-(void)didFindPeripheral:(YMSCBPeripheral *)peripheral
{
    NSLog(@"查找到了设备: %@", peripheral.name);
    
    @try {
        [self.findDevices addObject:peripheral];
        [self findPeripheralAndConnect];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"didFindPeripheral" object:nil userInfo:nil];
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }
    
//    @try {
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"didFindPeripheral" object:nil];
//    }
//    @catch (NSException *exception) {
//        NSLog(@"--------------------------------");
//    }
//    @finally {
//        
//    }
}

-(void)didDisconnectWithDevice
{
    NSLog(@"蓝牙断开连接...");
    self.hasConnected = NO;
    [self setCurrentPeripheralName:self.peripheral.name];
}

@end
